package pl.koziczak.knowledgeintegration.main;

import java.util.HashMap;
import java.util.Map;

import pl.koziczak.knowledgeintegration.exception.KnowledgeIntegrationException;

public class CommandLineArgumentParser {
	
	public static Map<CommandLineArgument,String> parse(String[] args) throws KnowledgeIntegrationException {
		Map<CommandLineArgument,String> result = new HashMap<CommandLineArgument, String>();
		if(args.length!=CommandLineArgument.getAll().size()*2)
			throw new KnowledgeIntegrationException("BAD NUMBER OF ARGUMENTS");
		for(CommandLineArgument arg : CommandLineArgument.getAll()) {
			int index = indexOf(arg.getPrompt(), args);
			if(index==-1 && arg.isRequired())
				throw new KnowledgeIntegrationException("NO ARGUMENT: " + arg.getPrompt());
			if(index+1 >= args.length)
				throw new KnowledgeIntegrationException("NO VALUE OF ARGUMENT: " + arg.getPrompt());
			result.put(arg, args[index+1]);
		}
		return result;
	}
	
	private static int indexOf(String arg, String args[]) {
		if(args==null || args.length==0)
			return -1;
		for(int i=0;i<args.length;i++) {
			if(args[i].equals(arg)) 
				return i;
		}
		
		return -1;
	}
	
}
